/**
 *
 */
let http = require("http");
const url = require("url");

let routes = [];
// TODO:
const next = () => {

 };
// 根据请求的路径匹配路由
const matchRouter = (path, req,res) => {
  routes && routes.forEach((item) => {
      if (item.path === path) {
        item.callback && item.callback(req, res, next);
        return
      }
    });
};
// 创建HTTP服务
const server = http.createServer((req, res) => {
  const urlObj = url.parse(req.url);
  if(req.method === 'GET'){
    matchRouter(urlObj.pathname, req, res);
  }else{
    req.on("data", function (data) {
      req.body = data;
      matchRouter(urlObj.pathname, req, res);
    });
  }
});
//监听API
const listen = (port, callback) => {
  server.listen(port);
  if (callback) {
    callback();
  }
};
// 调用user时候将path和对应的回调函数保存
const use = (path, callback) => {
  routes.push({
    path,
    callback,
    method: "all",
  });
};

// 指定方法
const Router = () => {
  return {
    get: (path, callback) => {
      routes.push({
        path,
        callback,
        method: "GET",
      });
    },
    post: (path, callback) => { },
    put: (path, callback) => { },
    patch: (path, callback) => { },
    delete: (path, callback) => { },
  };
};

module.exports = { listen, use, Router };
